package com.spark.tags;

import java.util.List;
import java.util.Map;

import com.spark.core.SparkContext;
import com.spark.core.XMap;

public class SwitchButton extends ViewComponent {
	
	public static final String TAG_NAME = "groupButton";
	public static final String PROPERTITY_ITEMS = "items";
	public static final String PROPERTITY_ACTIVE_VALUE = "activeValue";
	public static final String PROPERTITY_ALIGN = "align";
	
	private static final String DEFAULT_PROPERTITY_ALIGN = "h";
	
	private static final String DEFAULT_TEMPLATES = "switchButton.ftl";
	private static final String DEFAULT_CLASSNAME = "s-switch-button";
	
	public String getTemplate(){
		return DEFAULT_TEMPLATES;
	}
	
	protected String getDefaultClass(XMap view,SparkContext context){
		String className = super.getDefaultClass(view, context);
		StringBuilder sb = new StringBuilder();
		sb.append(className);
		if(!"".equals(className.trim()))sb.append(" ");
		sb.append(DEFAULT_CLASSNAME);
		return sb.toString();
	}
	
	public void init(XMap view, SparkContext context) throws Exception {
		super.init(view, context);
		XMap items = view.getChild(PROPERTITY_ITEMS);
		String av = view.getString(PROPERTITY_ACTIVE_VALUE);		
		if (items != null && items.getChilds() != null) {
			StringBuilder sb = new StringBuilder();
			List<XMap> children = items.getChilds();
			int i = 1,len = children.size();
			for (XMap item : children) {
				String value = item.getString("value","");
				String style = item.getString("style","");
				String text = item.getString("text","");
				sb.append("<li value=\"").append(value).append("\" ");
				sb.append("class=\"");
				if((av==null && i == 1) || value.equals(av)) {
					context.addJsonConfig(PROPERTITY_ACTIVE_VALUE,(av==null && i == 1) ? value : av);
					sb.append("cur");
				}
				if(i==len) {
					sb.append(" last");
				}
				sb.append("\" ");
				if(!"".equals(style)){
					sb.append("style=\"").append(style).append("\"");
				}
				sb.append(">").append(text).append("</li>");
				i++;
			}
			context.put(PROPERTITY_ITEMS, sb.toString());
		}
	}
	
	@SuppressWarnings("unchecked")
	protected String build(SparkContext context){
		Map map = context.getMap();
		StringBuilder sb = new StringBuilder();
		sb.append("<ul class=\"").append(get(map,"className")).append("\" style=\"").append(get(map,"style")).append(";\" id=\"").append(get(map,"id")).append("\">\r");
		sb.append("    ").append(get(map,"items"));
		sb.append("</ul>\r");
		sb.append("<script>new Spark.SwitchButton(").append(get(map,"config")).append(");</script>\r");
		return sb.toString();
	}
}
